<!-- 新增/修改弹框 -->
<template>
  <!-- 新增/修改弹窗 -->
  <el-dialog
    v-model="dialogVerifyImage.visible"
    :title="dialogVerifyImage.title"
    draggable
    :width="900"
    close-icon="CloseBold"
    :close-delay="200"
    style="margin-top: 15vh"
  >
    <el-row justify="center">
      <el-col :span="10" align="center">
        <div style="padding-left: 20%">
          <el-alert title="请在摄像头中对准人脸进行拍照" center type="warning" :closable="false" />

          <!--  显示照片  -->
          <div style="padding-top: 20px">
            <!-- 画笔控件 用来拍照 -->
            <canvas ref="canvasDom" style="display: none" />
            <!-- 播放器，用来播放拍摄的视频 -->
            <video v-if="!imgurl" ref="videoDom" class="camera_video" />
            <el-image v-else :src="imgurl" style="height: 200px; width: 200px"> </el-image>
          </div>

          <br />
          <div style="padding-top: 20px">
            <el-button v-if="imgurl" type="danger" :disabled="verifyLoading" @click="takePhoto">{{
              verifyLoading ? "正在验证..." : "重拍"
            }}</el-button>
            <el-button v-else type="primary" @click="takePhoto">拍照</el-button>
          </div>
        </div>
      </el-col>
      <el-col :span="4" align="center" style="padding-top: 36px">
        <el-result v-if="!isFirst && !verifyLoading && !checkResult" title="验证失败">
          <template #icon>
            <el-text type="error"><CircleClose /></el-text>
          </template>
          <template #sub-title>
            <p>请手动核验</p>
          </template>
        </el-result>
        <el-result v-if="!isFirst && !verifyLoading && checkResult" title="验证通过">
          <template #icon>
            <el-text type="success"><CircleCheck /></el-text>
          </template>
        </el-result>
        <el-result v-if="verifyLoading" title="验证中...">
          <template #icon>
            <el-text type="info"><Loading class="rotate-out-center" /></el-text>
          </template>
        </el-result>
      </el-col>
      <el-col :span="10" align="center">
        <div style="padding-right: 20%">
          <el-alert title="当前核验照片" center type="success" :closable="false" />
          <!--  显示照片  -->
          <div style="padding-top: 20px">
            <el-image :src="verifyPhoto" style="height: 200px; width: 200px"> </el-image>
          </div>

          <div style="padding-top: 20px">
            <el-button v-if="!isFirst && !verifyLoading && !checkResult" type="primary" @click="handleVerifyPersonImage"
              >手动核验</el-button
            >
          </div>
        </div>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script lang="ts" setup>
import { getImageByIdCard, getImageByIdCardVerify, updatePersonFacePhoto } from "@/api/system/face/index";
import { OnSiteVerification } from "@/api/group/index";
// canvas控件对象
const canvasDom = ref();
// video 控件对象
const videoDom = ref();
// 照片路径
const imgurl = ref();
// 校验结果
const checkResult = ref(false);
const checkMessage = ref("");
// 校验中
const verifyLoading = ref(false);
const isFirst = ref(true);

//当前核验照片
const verifyPhoto = ref("/static/jpg/avatar.jpg");

const props = defineProps({
  dialogVerifyImage: {
    type: Object,
    default: () => ({}),
  },
});
const emit = defineEmits(["sendClose"]);
const { dialogVerifyImage } = toRefs(props);

//验证照片
const veryfyPersonImage = (picBase64: string) => {
  verifyLoading.value = true;
  OnSiteVerification({ personId: dialogVerifyImage.value.personId, pic: picBase64 })
    .then((res) => {
      checkResult.value = res.success;
      checkMessage.value = res.msg;
      updatePersonFacePhoto(res.data, dialogVerifyImage.value.id).then((resp) => {
        if (resp.success === true) {
          ElMessage.success(resp.msg);
          // verifyPhoto.value = picBase64;
        } else {
          ElMessage.warning(resp.msg);
        }
      });
    })
    .finally(() => {
      isFirst.value = false;
      verifyLoading.value = false;
    });
};

const handleVerifyPersonImage = () => {
  ElMessage.success("已提交核验，需管理员审核");
};

//打开照相机
const openCamera = () => {
  // 检测浏览器是否支持mediaDevices
  if (navigator.mediaDevices) {
    navigator.mediaDevices
      // 开启视频，关闭音频
      .getUserMedia({ audio: false, video: true })
      .then((stream) => {
        // 将视频流传入viedo控件
        videoDom.value.srcObject = stream;
        // 播放
        videoDom.value.play();
      })
      .catch((err) => {
        console.log(err);
      });
  } else {
    ElMessageBox.alert("该浏览器不支持开启摄像头，请更换最新版浏览器", "提示");
  }
};

// 拍照
const takePhoto = () => {
  // 如果已经拍照了就重新启动摄像头
  if (imgurl.value) {
    imgurl.value = null;
    openCamera();
    return;
  }

  // 设置画布大小与摄像大小一致
  canvasDom.value.width = videoDom.value.videoWidth;
  canvasDom.value.height = videoDom.value.videoHeight;
  // 执行画的操作
  canvasDom.value.getContext("2d").drawImage(videoDom.value, 0, 0);
  // 将结果转换为可展示的格式
  imgurl.value = canvasDom.value.toDataURL("image/jpeg");
  // 关闭摄像头
  stop();
  veryfyPersonImage(imgurl.value);
};

// 关闭摄像头
const stop = () => {
  let stream = videoDom.value.srcObject;
  if (!stream) return;
  let tracks = stream.getTracks();
  tracks.forEach((x: any) => {
    x.stop();
  });
};
//初始化核验照片
const initVeifyPic = () => {
  if (dialogVerifyImage.value.id) {
    getImageByIdCardVerify(dialogVerifyImage.value.id)
      .then((res) => {
        if (res.success) {
          verifyPhoto.value = res.data;
        } else initIDCardPic();
      })
      .catch(() => {
        initIDCardPic();
      });
  }
};
//初始化身份证照片
const initIDCardPic = () => {
  getImageByIdCard(dialogVerifyImage.value.id).then((res) => {
    if (res.success) {
      verifyPhoto.value = res.data;
    }
  });
};

//初始化
onMounted(() => {
  openCamera();
  initVeifyPic();
});

/**
 * 关闭弹窗
 */
function closeDialog() {
  emit("sendClose");
}
</script>

<style lang="scss" scoped>
@-webkit-keyframes rotate-out-center {
  0% {
    -webkit-transform: rotate(-360deg);
    transform: rotate(-360deg);
  }
  100% {
    -webkit-transform: rotate(0);
    transform: rotate(0);
  }
}
@keyframes rotate-out-center {
  0% {
    -webkit-transform: rotate(-360deg);
    transform: rotate(-360deg);
  }
  100% {
    -webkit-transform: rotate(0);
    transform: rotate(0);
  }
}
.rotate-out-center {
  -webkit-animation: rotate-out-center 2s ease infinite both;
  animation: rotate-out-center 2s linear infinite both;
}

.camera_video {
  width: 200px;
  height: 200px;
}
</style>
